Masthead

Converting Files

To read a file, do conversions, and then write it back out again, we just have to add the code to write a file to our code from before that reads a file.

TheFile=open("C:/Temp/test.txt","r") # open the file for reading (thus the "r")
TheOutputFile=open("C:/Temp/output.csv","w") # open the output file for writing

TheOutputFile.write("Column1","Column2") # output the header line

NumLines=0
TheLine=TheFile.readline() # read the first line in the file
while ((TheLine!="") and (NumLines<100)): # while the line is not blank, go through this loop
	print(TheLine) 
	TheLine=TheFile.readline() # read the next line in the file

	TheCells=TheLine.split("\t") # split up the line

	# do conversions on the cells here.

	TheOutputFile.write(TheCells[0]+","+TheCells[1]) # output the line to the output file

	NumLines+=1 # add one to count the number of lines read

TheFile.close()
TheOutputFile.close() # close the file

print("Read "+format(NumLines)+" lines from the file")

 

Additional Resources

Python Documentation: String functions

Python Documentation: Defining Functions

 

© Copyright 2018 HSU - All rights reserved.